package com.luzhikun.java;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

/**
 * @author shkstart
 * @create 2021-03-28 19:08
 */
public class dom4jTest {
    @Test
    public void test1() {
        //创建一个saxReader流，去读取xml文件，生成document对象
        SAXReader sr = new SAXReader();
        try {
            Document read = sr.read("src/book.xml");
            System.out.println(read);

        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    @Test
    /*
     * 读取xml文件生成book类
     *
     * */
    public void test2() {
        //1.读取book.xml文件
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read("src/book.xml");
            //2.通过document对象获取根元素
            Element rootElement = read.getRootElement();
            //3.通过根元素获取book标签对象
            List<Element> book = rootElement.elements("book");
            //4.遍历，处理每个book标签转换成Book实例
            for (Element books : book) {
                //asXML()把标签对象转换成标签字符串
//                System.out.println(books.asXML());
                //获取xml文件的name标签
                Element name = books.element("name");
                //getText():可以获取标签中的文本内容
                String nametext = name.getText();
//              elementText()可以获取标签中的文本内容
                String authorText = books.elementText("author");

                String priceText = books.elementText("price");
                //attributeValue()可以获取标签属性
                String snText = books.attributeValue("sn");

                System.out.println(new Book(snText, nametext, authorText, Double.parseDouble(priceText)));

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }
}
